// 下载文章 Markdown 文件，返回下载链接
import axios from "axios";
import { request, requestWithErrorHandling } from "./request";

// 获取文章列表
export function fetchArticles(params = {}) {
  // 构建查询字符串
  const query = Object.entries(params)
    .filter(([_, v]) => v !== undefined && v !== null && v !== "")
    .map(([k, v]) =>
      Array.isArray(v)
        ? v
            .map(
              (item) => `${encodeURIComponent(k)}=${encodeURIComponent(item)}`
            )
            .join("&")
        : `${encodeURIComponent(k)}=${encodeURIComponent(v)}`
    )
    .join("&");
  return requestWithErrorHandling({
    url: `/search${query ? `?${query}` : ""}`,
    method: "get",
    errorMessage: "获取文章列表失败",
  }).then((res) => {
    // 适配后端返回的数据结构，统一转为驼峰
    function adapt(item) {
      return {
        ...item,
        // 兼容后端下划线和前端驼峰
        categoryName: item.categoryName || item.category_name || "",
        subCategoryName: item.subCategoryName || item.sub_category_name || "",
        tags: Array.isArray(item.tags)
          ? item.tags
          : typeof item.tags === "string"
          ? item.tags
              .split(/[,，]/)
              .map((t) => t.trim())
              .filter(Boolean)
          : [],
        username: item.username || "未知",
        createAt: item.createAt || item.create_at,
        updateAt: item.updateAt || item.update_at,
      };
    }
    if (res.code === 1 && res.data && Array.isArray(res.data.list)) {
      return {
        list: res.data.list.map(adapt),
        total:
          typeof res.data.total === "number"
            ? res.data.total
            : res.data.list.length,
      };
    } else if (res.code === 1 && res.data && res.data.list) {
      // 兼容对象结构
      return {
        ...res.data,
        list: Array.isArray(res.data.list) ? res.data.list.map(adapt) : [],
        total:
          typeof res.data.total === "number"
            ? res.data.total
            : Array.isArray(res.data.list)
            ? res.data.list.length
            : 0,
      };
    }
    return { list: [], total: 0 };
  });
}

// 下载文章Word，返回下载链接
export function downloadArticleWordById(id) {
  return requestWithErrorHandling({
    url: `/download/word/${id}`,
    method: "get",
    errorMessage: "获取Word下载链接失败",
  }).then((res) => {
    if ((res.code === 1 || res.code === 200) && res.data) {
      return res.data;
    }
    throw new Error(res.msg || "未获取到Word下载链接");
  });
}

// 下载文章Markdown，返回下载链接
export function downloadArticleMarkdownById(id) {
  return requestWithErrorHandling({
    url: `/download/markdown/${id}`,
    method: "get",
    errorMessage: "获取Markdown下载链接失败",
  }).then((res) => {
    if ((res.code === 1 || res.code === 200) && res.data) {
      return res.data;
    }
    throw new Error(res.msg || "未获取到Markdown下载链接");
  });
}

// 下载文章PDF，返回下载链接
export function downloadArticlePdfById(id) {
  return requestWithErrorHandling({
    url: `/download/pdf/${id}`,
    method: "get",
    errorMessage: "获取PDF下载链接失败",
  }).then((res) => {
    if ((res.code === 1 || res.code === 200) && res.data) {
      return res.data;
    }
    throw new Error(res.msg || "未获取到PDF下载链接");
  });
}

// 新增文章
export function createArticle(data) {
  return requestWithErrorHandling({
    url: "/articles",
    method: "POST",
    data: {
      title: data.title,
      content: data.content,
      username: data.username,
      subCategoryId: data.subCategoryId,
      tags: data.tags,
      status: data.status || 0,
    },
    errorMessage: "创建文章失败",
  });
}

// 编辑文章
export function updateArticle(data) {
  return requestWithErrorHandling({
    url: "/articles",
    method: "PUT",
    data: {
      id: data.id,
      title: data.title,
      content: data.content,
      username: data.username,
      subCategoryId: data.subCategoryId,
      tags: data.tags,
      status: data.status,
    },
    errorMessage: "更新文章失败",
  });
}

// 单独删除文章
export function deleteArticle(id) {
  return requestWithErrorHandling({
    url: `/articles/${id}`,
    method: "DELETE",
    errorMessage: "删除文章失败",
  });
}

// 批量删除文章
export function batchDeleteArticles(ids) {
  return requestWithErrorHandling({
    url: `/articles/batch/${ids}`,
    method: "DELETE",
    errorMessage: "批量删除失败",
  });
}

// 发布文章
export function publishArticle(id) {
  return requestWithErrorHandling({
    url: `/articles/publish/${id}`,
    method: "PUT",
    errorMessage: "发布文章失败",
  });
}

// 根据文章内容生成标签
export function generateTags(text) {
  return requestWithErrorHandling({
    url: "/generate/tags",
    method: "POST",
    data: { text: text },
    errorMessage: "标签生成失败",
  });
}

// 增加文章阅读量
export function increaseArticleView(id) {
  return requestWithErrorHandling({
    url: `/articles/view/${id}`,
    method: "PUT",
    errorMessage: "增加阅读量失败",
  });
}

// 根据ID获取文章详情
export function fetchArticleById(id) {
  return requestWithErrorHandling({
    url: `/articles/${id}`,
    method: "get",
    errorMessage: "获取文章详情失败",
  }).then((res) => {
    if (res.code === 1 && res.data) {
      return {
        ...res.data,
        tags: res.data.tags ? res.data.tags.split(",") : [],
        username: res.data.username || "未知",
        createAt: res.data.create_at || res.data.createAt,
        updateAt: res.data.update_at || res.data.updateAt,
        // 确保子分类ID字段被保留
        subCategoryId: res.data.subCategoryId || res.data.sub_category_id,
      };
    }
    return null;
  });
}

// 获取用户的文章列表
export function getUserArticles(userId, params = {}) {
  return requestWithErrorHandling({
    url: `/articles/user/${userId}`,
    method: "get",
    params,
    errorMessage: "获取用户文章失败",
  }).then((res) => {
    if (res.code === 1 && res.data) {
      const list = (res.data.list || []).map((item) => ({
        ...item,
        tags: item.tags ? item.tags.split(",") : [],
        createAt: item.createAt || item.create_at,
        updateAt: item.updateAt || item.update_at,
      }));
      return {
        list: list,
        total: res.data.total || 0,
      };
    }
    return { list: [], total: 0 };
  });
}
